package com.prawn.authority.dao;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;

import com.prawn.authority.pojo.Function;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;

import java.util.List;

/**
 * 数据访问接口
 * @author Administrator
 *
 */
public interface FunctionDao extends JpaRepository<Function,String>,JpaSpecificationExecutor<Function>{
    Function findFunctionById(String functionId);

    @Query(value = "SELECT f.`id`, f.`name`, f.`createDate`, f.`parentId`, f.`sort`, f.`href`, f.`remarks` FROM authority_function AS f, authority_function_role AS fr WHERE f.id = fr.`functionId` AND fr.roleId = ?;", nativeQuery = true)
	List<Function> findByRoleId(String roleId);

    //查找该角色可以授权的权限
    @Query(value = "SELECT f.* FROM authority_function f WHERE f.`id` NOT IN ( SELECT f.`id` FROM authority_role r,authority_function f,authority_function_role fr WHERE r.`id`=fr.`roleId` AND fr.`functionId` = f.`id` AND r.`id`= ?)",nativeQuery = true)
    List<Function> findOthersByRoleId(String roleId);

    //给角色授权
    @Modifying
    @Query(value = "INSERT INTO authority_function_role VALUES(?1, ?2)", nativeQuery = true)
    void addRoleFunction(String roleId,String functionId);

    //基地老板给基地用户授权
    @Modifying
    @Query(value = "INSERT INTO authority_base_role_function VALUES(?1, ?2,?3);", nativeQuery = true)
    void addBaseRoleFunction(String baseId,Integer baseIdentity,String functionId);

    //基地老板查询基地角色的权限
    @Modifying
    @Query(value = "SELECT f.* FROM authority_function f INNER JOIN authority_base_role_function fr  WHERE fr.baseId = ?1 AND fr.baseIdentity = ?2 AND fr.functionId = f.id", nativeQuery = true)
    List<Function> findFunctionByBase(String baseId,Integer baseIdentity);

    //通过权限Id删除基地用户权限
    @Modifying
    @Query(value = "DELETE FROM authority_base_role_function WHERE functionId = ?;" ,nativeQuery = true)
    void deleteBaseRoleFunctionByFunctionId(String functionId);

    @Modifying
    @Query(value = "SELECT functionId FROM authority_function_role WHERE roleId = ?",nativeQuery = true)
    List<Object> findFunctionIdByRoleId(String roleId);

    @Modifying
    @Query(value = "DELETE FROM authority_function_role WHERE functionId = ?1 AND roleId = ?2",nativeQuery = true)
    void deleteFunctionByRoleId(String functionId,String roleId);
}
